<template>
    <div id="app">
        <div class="leftBox">
            <img src="@/assets/svg/graphic1.svg">
        </div>
        <div class="rightBox">
            <div class="loginContent">
                <h3>思缘到家</h3>
                <p>欢迎登录思缘到家服务平台</p>
                <Form ref="usernameLoginForm">
                    <div class="form-item">
                        <input type="text" placeholder="账户" autocomplete="off" v-model="form.username">
                    </div>
                    <div class="form-item">
                        <input type="password" placeholder="密码" autocomplete="off"
                               v-model="form.password">
                    </div>
                    <div class="form-item" style="display: flex">
                        <input type="text" placeholder="验证码" autocomplete="off" v-model="form.code" style="width: 40%">
                        <img :src="captchaImg" @click="getCaptchaImg" style="margin-left: 10px;margin-bottom: 14px;">
                    </div>

                    <button type="button" @click="submitLogin">
                        <span v-if="!loading">登录</span>
                        <span v-else>登录中...</span>
                    </button>
                </Form>
            </div>
        </div>
    </div>
</template>

<script>
import {login, userInfo, initCaptcha, drawCodeImage} from "@/api/index";
import {validateMobile} from "@/libs/validate";
import Cookies from "js-cookie";
import Header from "@/views/main-components/header";
import Footer from "@/views/main-components/footer";
import LangSwitch from "@/views/main-components/lang-switch";
import CountDownButton from "@/views/my-components/scmt/count-down-button";
import util from "@/libs/util.js";
import Vue from 'vue'
import {removeToken, setToken} from '@/utils/auth'

export default {
    components: {
        CountDownButton,
        LangSwitch,
        Header,
        Footer,
    },
    data() {
        return {
            showMore: false,
            captchaId: "",
            captchaImg: "",
            loadingCaptcha: true,
            error: false,
            tabName: "username",
            saveLogin: true,
            getSms: "获取验证码",
            loading: false,
            sending: false,
            errorCode: "",
            form: {
                username: "",
                password: "",
                mobile: "",
                code: "",
            },
            rules: {
                username: [
                    {
                        required: true,
                        message: "账号不能为空",
                        trigger: "change",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: "密码不能为空",
                        trigger: "change",
                    },
                ],
                imgCode: [
                    {
                        required: true,
                        message: "验证码不能为空",
                        trigger: "change",
                    },
                ],
                mobile: [
                    {
                        required: true,
                        message: "手机号不能为空",
                        trigger: "change",
                    },
                    {
                        validator: validateMobile,
                        trigger: "change",
                    },
                ],
            },
        };
    },
    created() {
        // 绑定回车键
        window.addEventListener('keydown', this.keyDown)
    },
    destroyed() {
        window.removeEventListener('keydown', this.keyDown, false);
    },
    methods: {
        keyDown(e) {
            // 如果是回车则执行登录方法
            if (e.keyCode === 13) {
                this.submitLogin();
            }
        },
        getCaptchaImg() {
            this.loadingCaptcha = true;
            initCaptcha().then((res) => {
                this.loadingCaptcha = false;
                if (res.success) {
                    this.captchaId = res.data;
                    this.captchaImg = drawCodeImage + this.captchaId;
                }
            });
        },
        sendSmsCode() {
            this.$refs.mobileLoginForm.validate((valid) => {
                if (valid) {

                }
            });
        },
        submitLogin() {
            if (this.tabName == "username") {
                this.$refs.usernameLoginForm.validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        login({
                            username: this.form.username,
                            password: this.form.password,
                            code: this.form.code,
                            captchaId: this.captchaId,
                            saveLogin: this.saveLogin,
                        }).then((res) => {
                            if (res.success) {
                                setToken(res.data, true);
                                // 获取用户信息
                                userInfo().then((res) => {
                                    if (res.success) {
                                        // 避免超过大小限制
                                        delete res.data.permissions;
                                        let roles = [];
                                        res.data.roles.forEach((e) => {
                                            roles.push(e.name);
                                        });
                                        delete res.data.roles;
                                        this.setStore("roles", roles);
                                        this.setStore("saveLogin", this.saveLogin);

                                        this.$store.commit("setNickname", res.data.nickname);
                                        if (res.data.avatar) {
                                            this.$store.commit("setAvatar", "data:image/png;base64," + res.data.avatar);
                                        }
                                        //把头像和签名的base64先置为空，避免cookies无法存储， 在需要用到签名的地方，调用userInfo接口获取
                                        delete res.data.avatar;
                                        delete res.data.autograph;
                                        if (this.saveLogin) {
                                            // 保存1天
                                            Cookies.set("userInfo", JSON.stringify(res.data), {
                                                expires: 1,
                                            });
                                        } else {
                                            Cookies.set("userInfo", JSON.stringify(res.data));
                                        }
                                        this.setStore("userInfo", res.data);
                                        this.$store.commit("setUserInfo", res.data);
                                        let _this = this;
                                        util.initRouter(this, function (v) {
                                            _this.$store.commit("setMenuWidth", 220);
                                            let data = _this.$store.state.app.navList;
                                            if (data && data.length > 0) {
                                                if (data[0].children && data[0].children.length > 0 && data[0].children[0].children && data[0].children[0].children.length > 0) {
                                                    let path = "";
                                                    path = data[0].children[0].path == "/" ? "" : data[0].children[0].path;
                                                    path += /^\/./.test(data[0].children[0].children[0].path) ? data[0].children[0].children[0].path : "/" + data[0].children[0].children[0].path;
                                                    _this.setStore("firstPath", path);
                                                    _this.$router.replace({
                                                        path: path
                                                    });
                                                }
                                            } else {
                                                _this.$Modal.confirm({
                                                    title: '提示',
                                                    content: '当前角色未关联菜单，请联系管理员处理！',
                                                    onOk: () => {
                                                        _this.$Modal.remove()
                                                        _this.$store.commit("logout", _this);
                                                        _this.setStore("accessToken", "");
                                                        // 强制刷新页面 重新加载router
                                                        location.reload();
                                                    },
                                                    onCancel: () => {
                                                        _this.$Modal.remove()
                                                        _this.$store.commit("logout", _this);
                                                        _this.setStore("accessToken", "");
                                                        // 强制刷新页面 重新加载router
                                                        location.reload();
                                                    }
                                                });
                                                _this.loading = false;
                                            }
                                        });
                                    } else {
                                        this.loading = false;
                                    }
                                });
                            } else {
                                this.loading = false;
                                this.getCaptchaImg();
                            }
                        });
                    }
                });
            } else if (this.tabName == "mobile") {
                this.$refs.mobileLoginForm.validate((valid) => {
                    if (valid) {
                        if (this.form.code == "") {
                            this.errorCode = "验证码不能为空";
                            return;
                        } else {
                            this.errorCode = "";
                        }
                        this.form.saveLogin = this.saveLogin;

                    }
                });
            }
        },
        toGithubLogin() {

        },
        toQQLogin() {

        },
        toWeiboLogin() {

        },
        toWeixinLogin() {

        },
        toDingdingLogin() {

        },
        toWorkwechatLogin() {

        },
        relatedLogin() {
        },
        handleDropDown(v) {

        },
    },
    mounted() {
        this.relatedLogin();
        this.getCaptchaImg();
    },
};
</script>

<style lang="less">
@import "./login.less";
</style>
